﻿using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using GPS.GPS_DAL;

namespace GPS.Controllers.GPS_NghiepVu
{
    public class GPS_HocVienTotNghiepController : FDBController
    {
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        public ApplicationUser getCurrentUser()
        {
            ApplicationDbContext dbUser = new ApplicationDbContext();

            string userId = User.Identity.GetUserId();

            ApplicationUser _currentUser = dbUser.Users.Find(userId);

            return _currentUser;
        }
        #region Index

        /// <summary>
        /// Index
        /// </summary>
        /// <param name="SearchModel"></param>
        /// <param name="currentPage"></param>
        /// <param name="_form"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult Index(ViewModelHV_TOTNGHIEP SearchModel, int? currentPage, FormCollection _form, int? pagesize)
        {
            SearchModel.pDVGTVT_MA = this.getCurrentUser().MA_TINHTP;
            initialCategorySearchAction(SearchModel);

            if (SearchModel.SearchButton == "Phê duyệt thi tốt nghiệp")
            {


            }

            var entities = Singleton<GPS_DAL.GPS_HocVienDAO>.Inst.GPS_GETDS_HOCVIEN_DU_TOTNGHIEP(SearchModel.pDVGTVT_MA
                                                                                               , SearchModel.pKH_MA
                                                                                               , SearchModel.pHV_MA
                                                                                               , SearchModel.pHV_HOTEN
                                                                                               , SearchModel.pHV_CMND
                                                                                               , SearchModel.pHANG_DT
                                                                                               , SearchModel.pSO_QD_TN
                                                                                              );


            var pageIndex = SearchModel.Page ?? 1;
            int pageSize = pagesize ?? GPS.COMMON.Constants.PageSize;
            SearchModel.SearchResults = entities.ToPagedList(pageIndex, pageSize);

            ViewBag.TotalRow = entities.Count();
            ViewBag.CurrentPageSize = pageSize;

            return View(SearchModel);
        }


        /// <summary>
        /// Search
        /// </summary>
        /// <param name="SearchModel"></param>
        /// <param name="currentPage"></param>
        /// <param name="_form"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public ActionResult Search(ViewModelHV_TOTNGHIEP SearchModel, int? currentPage, FormCollection _form, int? pagesize)
        {
            if (SearchModel.pDVGTVT_MA == null)
                SearchModel.pDVGTVT_MA = "40";

            string _DVGTGT = this.getCurrentUser().MA_TINHTP;

            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MAQL == "40" && o.DVGTVT_ACTIVE == "1"), "DVGTVT_MA", "DVGTVT_TEN");
            ViewBag.DEFAULT_VALUE_DDL = CategoryCommon.DEFAULT_VALUE_DDL;

            //KH_MAs
            var khoahocs = Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN_TN(SearchModel.pDVGTVT_MA, SearchModel.pKH_MA);
            ViewBag.KH_MAs = new SelectList(khoahocs, "KH_MA", "KH_TEN");

            ViewBag.DTTN_QDs = new SelectList(_db.Filter<DDTTN_QD>(o => o.DDTTN_QD_DVGTVT_MA == SearchModel.pDVGTVT_MA && o.DDTTN_QD_TT == 1), "ID", "DDTTN_QD_TENKHOA");

            ViewBag.HANGDT_MAs = new SelectList(_db.Filter<SHANGDT>(o => o.HANGDT_RANK > 4), "HANGDT_MA", "HANGDT_TEN");

            var entities = Singleton<GPS_DAL.GPS_HocVienDAO>.Inst.GPS_GETDS_HOCVIEN_DU_TOTNGHIEP_SEARCH(SearchModel.pDVGTVT_MA
                                                                                               , SearchModel.pKH_MA
                                                                                               , SearchModel.pHV_MA
                                                                                               , SearchModel.pHV_HOTEN
                                                                                               , SearchModel.pHV_CMND
                                                                                               , SearchModel.pHANG_DT
                                                                                               , SearchModel.pSO_QD_TN
                                                                                               , SearchModel.pNGAY_QD_TUNGAY
                                                                                               , SearchModel.pNGAY_QD_DENNGAY
                                                                                              );


            var pageIndex = SearchModel.Page ?? 1;
            int pageSize = pagesize ?? GPS.COMMON.Constants.PageSize;
            SearchModel.SearchResults = entities.ToPagedList(pageIndex, pageSize);

            ViewBag.TotalRow = entities.Count();
            ViewBag.CurrentPageSize = pageSize;

            return View(SearchModel);
        }

        #region"Ajax"
        [HttpPost]
        public ActionResult getKH_MAs2(string ma_DVGT)
        {
            var districts = Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN(ma_DVGT).Select(a => "<option value='" + a.KH_MA + "'>" + a.KH_TEN + "</option>");
            var khoatotnghiep = _db.Filter<DDTTN_QD>(o => ((ma_DVGT == null || ma_DVGT == "40") || o.DDTTN_QD_DVGTVT_MA == ma_DVGT)).Select(a => "<option value='" + a.ID + "'>" + a.DDTTN_QD_TENKHOA + "</option>");
            var content = string.Join("", districts) + "#" + string.Join("", khoatotnghiep);
            return Content(content);
        }




        #endregion

        public void initialCategorySearchAction(ViewModelHV_TOTNGHIEP viewModel)
        {
            string Ma_GTVT = this.getCurrentUser().MA_TINHTP;
            ViewBag.DVGTVT_MAs = new SelectList(_db.Filter<SDONVIGTVT>(o => o.DVGTVT_MA == Ma_GTVT && o.DVGTVT_ACTIVE == "1"), "DVGTVT_MA", "DVGTVT_TEN");
            ViewBag.DEFAULT_VALUE_DDL = CategoryCommon.DEFAULT_VALUE_DDL;
           // var khoahocs = Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN1(viewModel.pDVGTVT_MA,viewModel.pKH_MA); // _db.Filter<DKH>(o => o.KH_DVGTVT_MA == viewModel.pDVGTVT_MA);

            var khoahocs = Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN_TN(viewModel.pDVGTVT_MA, viewModel.pKH_MA); // _db.Filter<DKH>(o => o.KH_DVGTVT_MA == viewModel.pDVGTVT_MA);
            ViewBag.KH_MAs = new SelectList(khoahocs, "KH_MA", "KH_TEN");

            ViewBag.DTTN_QDs = new SelectList(_db.Filter<DDTTN_QD>(o => o.DDTTN_QD_DVGTVT_MA == Ma_GTVT && o.DDTTN_QD_TT == 1), "ID", "DDTTN_QD_TENKHOA");

            ViewBag.HANGDT_MAs = new SelectList(_db.Filter<SHANGDT>(o => o.HANGDT_RANK > 4), "HANGDT_MA", "HANGDT_TEN");
        }
        #endregion

        #region"Approved"

        [HttpPost]
        public ActionResult Approved(JsonDataDDTTN a)
        {
            int _count = 0;
            string _pDVGTVT_MA;
            decimal _pSO_QD_TN;
            if (a != null)
            {
                if (a.Categories != null && a.Categories.Length > 0)
                {
                    int i = 0;
                    string[] Ids = JsonConvert.DeserializeObject<string[]>(a.Categories[0]);
                    _pDVGTVT_MA = Ids[0].Split('#')[0];
                    _pSO_QD_TN = a.DTTN_DTTN_QD_ID;
                    foreach (var _key in Ids)
                    {

                        var lstMA = _key.Split('#').ToList();
                        DDTTN _itemInsert = new DDTTN();
                        _itemInsert.ID = EFSequence.GetNextValue("SEQ_DDTTN_ID");
                        _itemInsert.DTTN_DVGTVT_MA = lstMA[0];
                        _itemInsert.DTTN_KH_MA = lstMA[1];
                        _itemInsert.DTTN_HV_MA = lstMA[2];
                        _itemInsert.DTTN_HGPLX_MA = lstMA[3];
                        _itemInsert.DTTN_HANGDT_MA = lstMA[4];
                        _itemInsert.DTTN_DTTN_QD_ID = a.DTTN_DTTN_QD_ID;
                        _itemInsert.DTTN_TT = "MOI";
                        _itemInsert.DTTN_NGAYNHAP = DateTime.Now;
                        _itemInsert.DTTN_NGUOINHAP = User.Identity.Name;

                        //insert vao bảng DKH_LOP_HV
                        _db.Insert<DDTTN>(_itemInsert);
                        //update trạng thái bảng DHV
                        //DHV _dhv = _db.GetOne<DHV>(o => o.HV_MA == _itemInsert.KH_LOP_HV_HV_MA && o.HV_DVGTVT_MA == _itemInsert.KH_LOP_HV_DVGTVT_MA);
                        //_dhv.HV_KH_LOP_MA = _itemInsert.KH_LOP_HV_KH_LOP_MA;
                        //_db.Update<DHV>(_dhv);

                        _count++;
                    }
                }
            }

            this.Information(string.Format("Đã phê duyệt [{0}] học viên được thi tốt nghiệp thành công!", _count));
            TempData["ThongBao"] = string.Format("Đã phê duyệt [{0}] học viên được thi tốt nghiệp thành công!", _count);
            //pDVGTVT_MA=40004&pSO_QD_TN=14&pagesize=25
            //string url = Url.Action("Index", "GPS_HocVienTotNghiep", new { pDVGTVT_MA = _pDVGTVT_MA, pSO_QD_TN = _pSO_QD_TN, pagesize = 25 });
            string url = Url.Action("Index", "GPS_HocVienTotNghiep");
            return Json(new { success = true, url = url });
            //   return Json("All the customers deleted successfully!");
        }


        public JsonResult UnApproved(decimal id)
        {

            _db.Delete<DDTTN>(o => o.ID == id);
            TempData["ThongBao"] = string.Format("Đã Hủy phê duyệt thi tốt nghiệp thành công 1 học viên  !");
            this.Information(string.Format("Đã Hủy phê duyệt thi tốt nghiệp thành công [{0}] học viên!", 1));
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        #endregion


        public ActionResult AddHocVienKhoaTruoc()
        {
            try
            {
                //string Ma_GTVT = this.getCurrentUser().MA_TINHTP;
                //ViewBag.DTTN_QDs = new SelectList(_db.Filter<DDTTN_QD>(o => o.DDTTN_QD_DVGTVT_MA == Ma_GTVT), "ID", "DDTTN_QD_SO_QD");
                string Ma_GTVT = this.getCurrentUser().MA_TINHTP;
                ViewBag.DTTN_QDs = new SelectList(_db.Filter<DDTTN_QD>(o => o.DDTTN_QD_DVGTVT_MA == Ma_GTVT), "ID", "DDTTN_QD_TENKHOA");
                var khoahocs = Singleton<GPS_HocVienDAO>.Inst.GPS_GETDS_KHOAHOC_HOCVIEN_LH(Ma_GTVT);
                ViewBag.KH_MAs = new SelectList(khoahocs, "KH_MA", "KH_TEN"); ;//new SelectList(_db.Filter<DKH>(d => d.KH_DVGTVT_MA == Ma_GTVT), "KH_MA", "KH_TEN");
                return PartialView("_AddHocVienKhoaTruoc");
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


        //[HttpPost]
        //public ActionResult AddHocVienKhoaTruoc(FormCollection _form)
        //{

        //    int _count = 0;
        //    foreach (var _key in _form.AllKeys)
        //    {
        //        List<string> lstMA = null;
        //        if (_key.StartsWith("chk_"))
        //        {
        //            lstMA = _form[_key].Split('#').ToList();
        //            DDTTN _itemInsert = new DDTTN();
        //            _itemInsert.ID = EFSequence.GetNextValue("SEQ_DDTTN_ID");
        //            _itemInsert.DTTN_KH_MA = lstMA[0];
        //            _itemInsert.DTTN_DVGTVT_MA = lstMA[1];
        //            _itemInsert.DTTN_HV_MA = lstMA[2];
        //            _itemInsert.DTTN_TT = lstMA[3];
        //            _itemInsert.DTTN_HGPLX_MA = lstMA[4];
        //            _itemInsert.DTTN_HANGDT_MA = lstMA[5];
        //            _itemInsert.DTTN_DTTN_QD_ID = Convert.ToDecimal(_form["DTTN_DTTN_QD_ID"]);
        //            _itemInsert.DTTN_NGAYNHAP = DateTime.Now;
        //            _itemInsert.DTTN_NGUOINHAP = User.Identity.Name;

        //            //insert vao bảng DKH_LOP_HV
        //            _db.Insert<DDTTN>(_itemInsert);

        //            _count++;
        //        }

        //    }

        //    TempData["ThongBao"] = string.Format("Đã thêm [{0}] học viên thi tốt nghiệp thành công!", _count);

        //    string url = Url.Action("Index", "GPS_HocVienTotNghiep");

        //    return Json(new { success = true, url = url });

        //}

        [HttpPost]
        public ActionResult AddHocVienKhoaTruoc(FormCollection _form)
        {

            int _count = 0;
            foreach (var _key in _form.AllKeys)
            {
                List<string> lstMA = null;
                if (_key.StartsWith("chk_copy_"))
                {
                    lstMA = _form[_key].Split('_').ToList();
                    DDTTN _itemInsert = new DDTTN();
                    _itemInsert.ID = EFSequence.GetNextValue("SEQ_DDTTN_ID");
                    _itemInsert.DTTN_KH_MA = lstMA[0];
                    _itemInsert.DTTN_DVGTVT_MA = lstMA[1];
                    _itemInsert.DTTN_HV_MA = lstMA[2];
                    _itemInsert.DTTN_TT = lstMA[3];
                    _itemInsert.DTTN_HGPLX_MA = lstMA[4];
                    _itemInsert.DTTN_HANGDT_MA = lstMA[5];
                    _itemInsert.DTTN_DTTN_QD_ID = Convert.ToDecimal(_form["DTTN_DTTN_QD_ID"]);
                    _itemInsert.DTTN_NGAYNHAP = DateTime.Now;
                    _itemInsert.DTTN_NGUOINHAP = User.Identity.Name;

                    //insert vao bảng DKH_LOP_HV
                    _db.Insert<DDTTN>(_itemInsert);

                    _count++;
                }

            }

            TempData["ThongBao"] = string.Format("Đã thêm [{0}] học viên thi tốt nghiệp thành công!", _count);
            this.Information(string.Format("Đã thêm [{0}] học viên được thi tốt nghiệp thành công!", _count));
            string url = Url.Action("Index", "GPS_HocVienTotNghiep");

            return Json(new { success = true, url = url });
            //return RedirectToAction("Index");
        }

        #region"Ajax"
        [HttpPost]
        public ActionResult getHocVienKyTruoc(string keysearch, string kh_ma)
        {
            var _keysearh = keysearch.ToUpper();
            string Ma_GTVT = this.getCurrentUser().MA_TINHTP;
            var john = Singleton<GPS_DAL.GPS_HocVienDAO>.Inst.GPS_GETDS_HOCVIEN_KYTRUOC(keysearch, kh_ma, Ma_GTVT);

            return Json(new { hocviens = john }, JsonRequestBehavior.AllowGet);

        }
        //[HttpPost]
        //public ActionResult getHocVienKyTruoc(string keysearch)
        //{
        //    var _keysearh = keysearch.ToUpper();
        //    var john = Singleton<GPS_DAL.GPS_HocVienDAO>.Inst.GPS_GETDS_HOCVIEN_KYTRUOC(keysearch);

        //    return Json(new { hocviens = john }, JsonRequestBehavior.AllowGet);

        //}

        [HttpPost]
        public ActionResult getKH_MAs(string ma_DVGT)
        {
            var districts = _db.Filter<DKH>(d => d.KH_DVGTVT_MA == ma_DVGT).Select(a => "<option value='" + a.KH_MA + "'>" + a.KH_MA + "</option>");

            return Content(string.Join("", districts));
        }



        //get Học viên
        [HttpPost]
        public ActionResult getHV_MAs(string Ma_DVGT, string ma_KH, string ma_LOP)
        {
            List<ModelDHV> _lst = Singleton<GPS_DAL.GPS_HocVienDAO>.Inst.GetdataHocVienInLop(Ma_DVGT, ma_KH, ma_LOP);
            var districts = _lst.Select(a => "<option value='" + a.HV_MA + "'>" + a.HV_HODEM + " " + a.HV_TEN + "</option>"); ;

            return Content(string.Join("", districts));
        }

        #endregion
    }

    public class JsonDataDDTTN
    {
        public decimal DTTN_DTTN_QD_ID { get; set; }
        public string[] Categories { get; set; }
    }
}